//#ifdef H5
const ua = navigator.userAgent;

//#endif
function getSystemInfoSync () {
    try {
        const result = uni.getSystemInfoSync();
        return Promise.resolve(result)
    } catch (e) {
        return new Promise(resolve => {
            uni.getSystemInfo({
                complete (res) {
                    resolve(res)
                }
            })
        })
    }
}

const Device = function () {
    const basic = {};
    let isWindowsPhone, isSymbian, isAndroid,
        isIpad, isIpod, isIphone, isAlipay, isWechat, isMiniWechat,
        isTablet, isPc, isChrome, isFireFox,
        SystemInfo;
    //#ifdef H5
    isWindowsPhone = /(?:Windows Phone)/.test(ua);
    isChrome = /(?:Chrome|CriOS)/.test(ua);
    isFireFox = /(?:Firefox)/.test(ua);
    isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone;
    isAndroid = /(Android);?[\s/]+([\d.]+)?/.test(ua);
    isIpad = /(iPad).*OS\s([\d_]+)/.test(ua);
    isIpod = /(iPod)(.*OS\s([\d_]+))?/.test(ua);
    isIphone = !isIpod && /(iPhone\sOS)\s([\d_]+)/.test(ua);
    isAlipay = /alipayclient/i.test(ua);
    isWechat = /micromessenger/i.test(ua);
    isMiniWechat = !!isWechat && (window.__wxjs_environment === 'miniprogram'
        || /__wxjs_environment=miniprogram/ig.test(window.location.search)
        || /#miniprogram/ig.test(window.location.href));
    isPc = !isAndroid && !isSymbian && !isIpad && !isIpod && !isIphone;
    isTablet = /(?:iPad|PlayBook)/.test(ua)
        || (isAndroid && !/(?:Mobile)/.test(ua))
        || (isFireFox && /(?:Tablet)/.test(ua));
    //#endif
    try {
        SystemInfo = uni.getSystemInfoSync();
        //#ifndef H5
        isAndroid = /^Android/.test(SystemInfo.model);
        isIphone = /^iPhone/.test(SystemInfo.model);
        //#endif
    } catch (e) {

    }
    return {
        isWindowsPhone,
        isSymbian,
        isAndroid,
        isIpad,
        isIpod,
        isIphone,
        isAlipay,
        isWechat,
        isMiniWechat,
        isChrome,
        isPc,
        isTablet,
        SystemInfo,
        ...basic
    };
};
export const device = Device();
export const deviceAsync = function () {
    if (device.SystemInfo) return Promise.resolve(device);
    return new Promise(resolve => {
        uni.getSystemInfo({
            complete (res) {
                device.SystemInfo = res;
                //#ifndef H5
                device.isAndroid = /^Android/.test(res.model);
                device.isIphone = /^iPhone/.test(res.model);
                //#endif
                resolve(device)
            }
        })
    })
};
export default device;
